import React, { Component } from 'react'
import { Tree , MessageBox , Input, Button , Table , Form ,Tag , Select,Message,Pagination} from "element-react" ;
import PubSub from "pubsub-js";
import { endsWith } from 'core-js/library/es7/string';


const Devicepageurl = "/device/devicemanageinfo/"

class Deviceinfo extends Component {
    state = {
      dialogVisible: false,
      form: {
        label: '',
        type: ''
      },
      data: [],
      options: {
        children: 'children',
        label: 'label'
      },
    }
  
    netcontorll = new AbortController()
  
    componentDidMount(){
     fetch("/device/devicebaiseinfo/devicelist")
      .then(data => data.json())
      .then(result=>{
        this.setState({data:result.data});
      })
    }
    componentWillUnmount(){
      //防止组件加载网络还未出结果组件就被卸载了导致的异常
      this.netcontorll.abort()
    }
    append(store, data ) {
    }
    
    addDevice = async (data)=>{
  
    }
  
  
  
    remove = (nodeModel ,store, data )=> {
    } 
  
    getTopId(node , tree){
      if(node.data.level===0) {
        return node.data.id;
      }
      return this.getTopId(tree.root.store.getNode(node.data.parent) , tree) ;
    }
    nodeClicked(data, node , tree){
      let topid = this.getTopId(tree.root.store.getNode(data.id) , tree)
      console.log(topid) ;
        if(data.children.length===0) {
          data.topid = topid ;
          PubSub.publish("device-info" , data);
        }
    }

    removeDevice = (ids , store , data )=>{
    }
    render() {
      
      const { data, options } = this.state
      return (
        <div>
          <Input placeholder="输入关键字进行过滤" onChange={text=> this.tree.filter(text)} />
          <Tree
            ref={e=> this.tree = e}
            data={data}
            options={options}
            nodeKey="id"
            expandOnClickNode={true}
            highlightCurrent={true}
            onNodeClicked={(data, node)=>{this.nodeClicked(data, node ,this.tree)}}
            filterNodeMethod={(value, data)=>{
              if (!value) return true;
              return data.label.indexOf(value) !== -1;
            }}
          />
        </div>
      )
    }
  }



export default class LendProcesspage extends Component {
  
    componentDidMount(){
        this.pubsubid = PubSub.subscribe("device-info",(msg , value)=>{
          fetch("/device/devicemanageinfo/currlistprocess" , {
            method:"POST",
            headers:{
              "Content-Type": "application/json",
            },
            body:JSON.stringify({type:value.id})
          }).then(data=>data.json())
          .then(result =>{
            console.log(result) ;
            result.page.list.map((e)=>{
              e.lable = value.label
              return e 
            })
            this.setState({data:result.page.list,currentnode:value ,topid:value.topid, page :{
              total: result.page.totalPage,
              pageSize:  result.page.pageSize,
              currentPage: result.page.currPage,
            }})
          })  
          fetch("/device/devicemanageinfo/currlistprocess" , {
            method:"POST",
            headers:{
              "Content-Type": "application/json",
            },
            body:JSON.stringify({page:1})
          }).then(data=>data.json())
          .then(result=>{
            console.log(result)
          })
        });
        fetch("/device/userbaiseinfo/getcurrentuserinfo")
        .then(data=>data.json())
        .then(result=>{
          this.setState({currnetUser:result.user})
        })
      }
    
      componentWillUnmount(){
        PubSub.unsubscribe(this.pubsubid);
      }
    
      statusmap = {
        0 : {tag:"success" ,
              name:"在库"} , //在库
        1 : {tag:"danger",
              name :"维修中"} ,  // 维修中
        2 : { tag:"primary" ,
              name : "借出" } , //借出
        3 : {tag:"gray" ,
              name:"不可用"}, //不可用
        4 : {tag:"primary" ,
              name:"审批中"},
        5 : {tag:"success" ,
              name:"审批通过"},
        6 : {tag:"danger" ,
              name:"审批未通过" },
        7 : {tag:"danger" ,
              name:"设备归还" },   

      }
      state = {
        currnetUser:{},
        columns: [
          {
            label: "设备编号",
            prop: "id",
            width: 200,
            fixed: 'left',
            align: 'center'
          },
          {
            label: "标签",
            prop: "lable",
            width: 160,
            align: 'center'
          },
          {
            label: "位置",
            prop: "location",
            align:"center",
            width: 400
          },
          {
            label: "状态",
            prop: "status",
            align: 'center',
            width: 100,
            render: (row, column, index)=>{
              return (
                <Tag
                type={this.statusmap[row.status].tag}
                >{
                  row.lendrecord===null ?this.statusmap[row.status].name : row.processname
                }</Tag>
              )
            },
          },
          {
            label: "周期",
            prop: "period",
            width: 120,
            align: 'center'
          },
          {
            label:"个人操作",
            render:(row ,col , index)=>{
              let option = {}
              return (
                <Button type='text' 
                  disabled={row.option.length===0}
                  onClick={()=>{
                  console.log(row)
                  MessageBox.msgbox({
                    showCancelButton:true,
                    message:(
                      <Form>
                        <Form.Item>
                          <Select onChange={e=>option = e}>
                            {
                              row.option.map(el=>{
                                return < Select.Option
                                          key={el.id}
                                          value={el.statuscode}
                                          label={el.optionname}
                                        />
                              })
                            }
                          </Select>
                        </Form.Item>
                      </Form>
                    )
                  }).then(action=>{
                    if(action==="confirm") {
                      row.lendrecord.status = option
                  fetch("/device/devicelendrecord/approverprocess" , {
                    method:"POST",
                    headers:{
                      "Content-Type": "application/json",
                    },
                    body:JSON.stringify(
                      row.lendrecord 
                    )
                  }).then(data=>data.json())
                  .then(reuslt=>{
                      Message({
                        type:reuslt.msg,
                        message:"操作成功"
                      })
                  })
                    }
                  })
                }}>操作</Button>
              )
            }
          },
          {
            label: "操作",
            width: 120,
            fixed: 'right',
            render: (row, column, index)=>{
                return (  
                    <span>
                        <Button 
                        type="text" size="small" 
                        onClick={()=>{
                          this.lendDevice(index)
                        }}
                        disabled={!(row.status===0)}
                        >
                          借用
                        </Button>
                    </span>
                )
            },
            align: 'center'
          }
        ],
        data: [] ,
        page:{} ,
        currentnode:{},
        from :{
          location:"",
          period:"",
        }
      }
      backDevice(index) {
        MessageBox.confirm('确定归还设备？', '提示', {
          type: 'warning'
        }).then(() => {
          fetch("/device/devicemanageinfo/cancelbackapprover",{
            method:"POST",
            headers:{
              "Content-Type": "application/json",
            },
            body:JSON.stringify({id:this.state.data[index].id , status:0})
          })
          Message({
            type: 'success',
            message: '操作!'
          });
        }).catch(() => {
          Message({
            type: 'info',
            message: '操作取消'
          });
        });
      }
      canceLend(index){
        MessageBox.confirm('是否取消申请', '提示', {
          type: 'warning'
        }).then(() => {
          fetch("/device/devicemanageinfo/cancelapprover",{
            method:"POST",
            headers:{
              "Content-Type": "application/json",
            },
            body:JSON.stringify({id:this.state.data[index].id , status:0})
          })
          Message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          Message({
            type: 'info',
            message: '操作取消'
          });
        });
      }
    
      lendDevice =(index)=> {
        MessageBox.msgbox({
          title: '操作',
          message: (
            <Form>
              <Form.Item>
                <Input 
                   onChange={(e)=>{this.approvermsg = e}}
                   type="textarea"
                   autosize={{ minRows: 10, maxRows: 10}}
                   placeholder="请输入申请事由"
                   resize="none"
                ></Input>
              </Form.Item>
            </Form>
          ),
          showCancelButton: true
        }).then(action=>{
          
          if(action==="confirm") {
            fetch("/device/devicelendrecord/save",{
              method:"POST",
              headers:{
                "Content-Type": "application/json",
              },
              body:JSON.stringify({
                deviceid:this.state.data[index].id,
                approverid:this.state.topid,
                status:0,
                msg:this.approvermsg,
                end:0 
              })
            }).then(data=>data.json())
            .then(result=>{
              this.state.data[index].status = 2 ;
              this.setState({data:[...this.state.data]})
              Message(
                {
                  type:result.msg,
                  message:"操作成功"
                }
              )
            })
          }
        })
      }
      pagechange = (currentPage)=>{
        fetch("/device/devicemanageinfo/currlistprocess",{
          method:"POST",
          headers:{
            "Content-Type": "application/json",
          },
          body:JSON.stringify({type:this.state.currentnode.id , page:currentPage})
        }).then(data=>data.json())
        .then(result =>{
          result.page.list.map((e)=>{
            e.lable = this.state.currentnode.label
            return e 
          })
          this.setState({data:result.page.list , page :{
            total: result.page.totalPage,
            pageSize:  result.page.pageSize,
            currentPage: result.page.currPage,
          }})
    
        })
      }
      // statusmap = []
      getstatusmap = ()=> {
        fetch("/device/devicestatusinfo/list")
        .then(data=>data.json())
        .then(result=>{
           let statusmap  = {}  
           result.list.map(el=>{
                statusmap[el.statuscode] = {
                    name : el.name ,
                    tag:el.tag
                }
                return el
            })
            this.statusmap  = statusmap
        })
      }
      render() {
        return (
          <div className='page' >
             <div className='databar' >
              <Deviceinfo/>
             </div>
             <div className='datatable' >
               <div>
                  <Button onClick={this.addDevice}>新增</Button>
               </div>
               {/* <Button>新增</Button> */}
              <Table
                style={{width: '100%'}}
                columns={this.state.columns}
                data={this.state.data}
                border={true}
                maxHeight={550}
              />
               <div className="block" style={{}}>
                <Pagination layout="prev, pager, next" 
                 pageCount={this.state.page.total} 
                 pageSize={this.state.pageSize}
                 currentPage={this.state.currentPage}
                 onCurrentChange={this.pagechange}/>
               </div>
             </div>
          </div>
        )
      }
}
